package pl.grumpy.tvforecast;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

enum state {
	unknown, series, seriesId, seriesName, overview, banner
};

public class TVSeriesHandler extends DefaultHandler {
	private TVSerie tvSerie = null;
	private List<TVSerie> tvSeries = new ArrayList<TVSerie>();
	private state myState = state.unknown;

	public List<TVSerie> getTvSeries() {
		return tvSeries;
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		super.characters(ch, start, length);
		if (myState != state.unknown) {
			String textNode = new String(ch, start, length);
			switch (myState) {
			case seriesId:
				tvSerie.setId(Integer.parseInt(textNode));
				myState = state.unknown;
				break;
			case seriesName:
				tvSerie.setTitle(textNode);
				myState = state.unknown;
				break;
			case overview:
				tvSerie.setDescription(textNode);
				myState = state.unknown;
				break;
			case banner:
				tvSerie.setBanner(textNode);
				Log.v("------------", "Got Banner!" + tvSerie.getTitle());
				myState = state.unknown;
				break;
			}
		}
	}

	@Override
	public void endDocument() throws SAXException {
		super.endDocument();
		// Log.v("TV Forecast", "endDoc\n" + tvSeries.toString());
		// TODO: jak nic nie znajdzie to doda puste i jest zonk!
		tvSeries.add(tvSerie); // nie zapominajmy o ostatnim elemencie
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		super.endElement(uri, localName, qName);
	}

	@Override
	public void startDocument() throws SAXException {
		super.startDocument();
		// Log.v("TV Forecast", "startDoc");
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		super.startElement(uri, localName, qName, attributes);
		if (localName.equals("SeriesName"))
			myState = state.seriesName;
		else if (localName.equals("seriesid"))
			myState = state.seriesId;
		else if (localName.equals("Overview"))
			myState = state.overview;
		else if (localName.equals("banner"))
			myState = state.banner;
		else if (localName.equals("Series")) {
			if (tvSerie != null)
				tvSeries.add(tvSerie);
			tvSerie = new TVSerie();
			myState = state.series;
		}
	}

}
